package me.lwn.auth.security.oauth2.server.authorization;

import me.lwn.auth.security.core.userdetails.User;
import me.lwn.auth.security.oauth2.server.authorization.oidc.authentication.DefaultOidcUserInfoMapper;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.server.authorization.JwtEncodingContext;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenCustomizer;
import org.springframework.security.oauth2.server.authorization.oidc.authentication.OidcUserInfoAuthenticationContext;
import org.springframework.util.StringUtils;

/**
 * 设置自定义token携带的信息，相关匹配自定义项需要同步设置到
 * DefaultOidcUserInfoMapper类getClaimsRequestedByScope方法中scopeRequestedClaimNames变量中
 * {@link DefaultOidcUserInfoMapper}
 *
 * @see DefaultOidcUserInfoMapper#apply(OidcUserInfoAuthenticationContext)
 */
public class CustomOAuth2TokenCustomizer implements OAuth2TokenCustomizer<JwtEncodingContext> {

    private final UserDetailsService userDetailsService;

    public CustomOAuth2TokenCustomizer(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    public void customize(JwtEncodingContext context) {

        // TODO 此处自定义token中携带的信息，根据需求进行自定义设置
        // 添加一个自定义头
        context.getHeaders().header("client-id", context.getRegisteredClient().getClientId());
        // 添加一个token主体中的信息
        if (StringUtils.hasText(context.getPrincipal().getName())) {
            User user = (User) userDetailsService.loadUserByUsername(context.getPrincipal().getName());
            context.getClaims().claim("name", user.getName());
        }
    }
}